<template>
  <div class="user-profile-page">
    <div class="header">
      <h1>用户中心 - 我的作品与评价</h1>
      <p v-if="currentUserId">当前登录用户 ID: {{ currentUserId }}</p>
      <p v-else class="login-prompt">请先登录以查看您的个人资料。</p>
    </div>

    <div v-if="loading" class="loading-state">
      <p>数据加载中，请稍候...</p>
    </div>

    <div v-else-if="!currentUserId" class="content-locked">
      <p>您尚未登录。请登录后查看您的创作和评分记录。</p>
      <button @click="router.push('/user/login')" class="btn-login">去登录</button>
    </div>

    <div v-else class="profile-content">
      <!-- 用户的创作历史 -->
      <section class="user-creations">
        <h2>🎨 我的创作历史 ({{ userCreations.length }} 条)</h2>
        <div v-if="userCreations.length > 0" class="creation-list">
          <div v-for="creation in userCreations" :key="creation.id" class="creation-card">
            <!-- 假设 finalOutputUrl 存储了创作结果图 -->
            <img
              :src="creation.finalOutputUrl || '/placeholder.jpg'"
              alt="创作预览"
              class="creation-preview"
            />
            <p>模板 ID: {{ creation.templateId }}</p>
            <p>纹理 ID: {{ creation.textureId }}</p>
            <p class="creation-time">创建于: {{ formatTime(creation.creationTime) }}</p>
          </div>
        </div>
        <p v-else>您还没有任何创作记录。</p>
      </section>

      <!-- 用户的评分历史 -->
      <section class="user-ratings">
        <h2>⭐ 我的模板评分 ({{ userRatings.length }} 条)</h2>
        <div v-if="userRatings.length > 0" class="rating-list">
          <div v-for="rating in userRatings" :key="rating.papercut.id" class="rating-card">
            <p>
              模板名称:
              <strong>{{ rating.papercut?.name || '模板 ' + rating.papercut?.id }}</strong>
            </p>
            <p>
              我的评分: <span class="rating-value">{{ '⭐'.repeat(rating.ratingValue) }}</span> ({{
                rating.ratingValue
              }}
              / 5)
            </p>
            <p class="review-text">评论: {{ rating.reviewText || '无' }}</p>
            <p class="rating-time">评论时间: {{ formatTime(rating.reviewTime) }}</p>

            <!-- 评分操作：点击重新打分 -->
            <button @click="openRatingModal(rating.papercut?.id)" class="btn-rate-again">
              修改评分
            </button>
          </div>
        </div>
        <p v-else>您还没有对任何模板进行评分。</p>
      </section>
    </div>

    <!-- 评分/评论模态框 (简单模拟) -->
    <div v-if="isRatingModalOpen" class="modal-overlay" @click.self="isRatingModalOpen = false">
      <div class="rating-modal">
        <h3>对模板 {{ ratingModal.templateId }} 打分</h3>
        <p>您的评分 (1-5):</p>
        <input type="number" v-model.number="ratingModal.value" min="1" max="5" />
        <p>您的评论:</p>
        <textarea v-model="ratingModal.review" rows="3"></textarea>

        <button @click="submitRating" :disabled="isSubmitting" class="btn-submit-rating">
          {{ isSubmitting ? '提交中...' : '提交评分' }}
        </button>
        <p
          v-if="ratingModalMessage"
          :class="ratingModalStatus === 'success' ? 'success-msg' : 'error-msg'"
        >
          {{ ratingModalMessage }}
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// 导入用户 ID 获取和用户创作 API
import { getCurrentUserId, getUserCreations, getUserRatings } from '@/api/userApi'
// 导入评分提交 API
import { submitRatingApi } from '@/api/ratingApi'

const router = useRouter()

const currentUserId = ref(null)
const loading = ref(true)
const userCreations = ref([]) // 用户创作历史列表
const userRatings = ref([]) // 用户评分历史列表

// 评分模态框状态
const isRatingModalOpen = ref(false)
const isSubmitting = ref(false)
const ratingModal = ref({
  templateId: null,
  value: 5,
  review: '',
})
const ratingModalMessage = ref('')
const ratingModalStatus = ref('')

/**
 * 步骤 0: 获取当前登录用户 ID (与 CreationEditor 逻辑一致)
 */
const fetchCurrentUserId = async () => {
  try {
    const res = await getCurrentUserId()
    currentUserId.value = res.data.id
  } catch (error) {
    console.error('获取当前用户 ID 失败:', error)
    currentUserId.value = null
  }
}

/**
 * 步骤 1: 获取用户的所有数据 (创作和评分)
 */
const fetchUserData = async () => {
  loading.value = true

  await fetchCurrentUserId() // 确保先拿到 ID

  if (!currentUserId.value) {
    loading.value = false
    return
  }

  try {
    const [creationsRes, ratingsRes] = await Promise.all([
      getUserCreations(currentUserId.value),
      getUserRatings(currentUserId.value), // 🚨 假设这个 API 已在后端实现
    ])

    userCreations.value = creationsRes.data.map((c) => ({
      ...c,
      // 🚨 假设后端返回的创作对象包含 templateId 和 textureId
      templateId: c.templateId || c.basePapercut?.id,
      textureId: c.textureId || c.selectedTexture?.id,
    }))

    // 🚨 假设评分数据结构正确
    userRatings.value = ratingsRes.data
  } catch (error) {
    console.error('加载用户数据失败:', error)
    alert('加载个人资料失败，请重试。')
  } finally {
    loading.value = false
  }
}

/**
 * 格式化时间显示
 */
const formatTime = (time) => {
  if (!time) return 'N/A'
  // 假设后端返回的是 ISO 字符串
  return new Date(time).toLocaleDateString() + ' ' + new Date(time).toLocaleTimeString()
}

/**
 * 打开评分模态框
 */
const openRatingModal = (templateId) => {
  ratingModal.value.templateId = templateId
  ratingModal.value.value = 5 // 默认 5 星
  ratingModal.value.review = ''
  ratingModalMessage.value = ''
  ratingModalStatus.value = ''
  isRatingModalOpen.value = true
}

/**
 * 提交评分
 */
const submitRating = async () => {
  if (!currentUserId.value || !ratingModal.value.templateId || ratingModal.value.value === null) {
    alert('用户ID、模板ID或评分值缺失！')
    return
  }
  if (ratingModal.value.value < 1 || ratingModal.value.value > 5) {
    alert('评分值必须在 1 到 5 之间！')
    return
  }

  isSubmitting.value = true
  ratingModalMessage.value = '提交中...'

  const ratingData = {
    userId: currentUserId.value,
    templateId: ratingModal.value.templateId, // 对应后端 papercut.id
    ratingValue: ratingModal.value.value,
    reviewText: ratingModal.value.review,
  }

  try {
    const res = await submitRatingApi(ratingData)
    ratingModalStatus.value = 'success'
    ratingModalMessage.value = res.data // "评分提交/更新成功"

    // 成功后延迟关闭并刷新数据
    setTimeout(() => {
      isRatingModalOpen.value = false
      fetchUserData() // 刷新用户评分历史
    }, 1000)
  } catch (error) {
    ratingModalStatus.value = 'error'
    ratingModalMessage.value = `提交失败: ${error.response?.data || error.message}`
    console.error('提交评分失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

onMounted(fetchUserData)
</script>

<style scoped>
/* 样式仅为示例，请根据项目自行调整 */
.user-profile-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: sans-serif;
}

.header {
  border-bottom: 2px solid #007bff;
  padding-bottom: 15px;
  margin-bottom: 30px;
}

.login-prompt {
  color: #dc3545;
  font-weight: bold;
}

.content-locked {
  text-align: center;
  padding: 30px;
  border: 1px dashed #ccc;
  border-radius: 8px;
}
.btn-login {
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 0px;
}

.profile-content section {
  margin-bottom: 0px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background-color: #fff;
}

.profile-content h2 {
  color: #333;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

/* 创作列表样式 */
.creation-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.creation-card {
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 8px;
  width: 250px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.creation-preview {
  height: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 5px;
}

.creation-time {
  font-size: 0.8em;
  color: #666;
}

/* 评分列表样式 */
.rating-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.rating-card {
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 8px;
  position: relative;
}

.rating-value {
  color: gold;
  font-size: 1.2em;
}

.review-text {
  font-style: italic;
  margin-top: 5px;
  color: #555;
}

.btn-rate-again {
  background-color: #ffc107;
  color: #333;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.rating-modal {
  background-color: white;
  padding: 10px;
  border-radius: 10px;
  width: 400px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.rating-modal input[type='number'],
.rating-modal textarea {
  width: 90%;
  padding: 8px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.btn-submit-rating {
  background-color: #28a745;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.success-msg,
.error-msg {
  margin-top: 10px;
  font-weight: bold;
}
.success-msg {
  color: #28a745;
}
.error-msg {
  color: #dc3545;
}
</style>
